package cn.yshujia.service.impl;

import cn.yshujia.domain.entity.Album;
import cn.yshujia.domain.entity.Article;
import cn.yshujia.domain.entity.Develop;
import cn.yshujia.domain.vo.AlbumVO;
import cn.yshujia.domain.vo.ArticleVO;
import cn.yshujia.domain.vo.SearchVO;
import cn.yshujia.mapper.AlbumMapper;
import cn.yshujia.mapper.ArticleMapper;
import cn.yshujia.mapper.DevelopMapper;
import cn.yshujia.repository.AlbumRepository;
import cn.yshujia.repository.ArticleRepository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author YShuJia
 * @create 2025/3/25
 * @description ClassifyLabelServiceImpl
 */

@Slf4j
@Service
public class ServiceServiceImpl {
	
	@Resource
	private AlbumMapper albumMapper;
	
	@Resource
	private DevelopMapper developMapper;
	
	@Resource
	private ArticleMapper articleMapper;
	
	@Resource
	private ArticleRepository articleRepository;
	
	@Resource
	private AlbumRepository albumRepository;
	
	@Resource (name = "Task")
	private Executor executor;
	
	public SearchVO searchByTask(String content) {
		SearchVO searchVO = new SearchVO();
		CompletableFuture<List<AlbumVO>> album = getAlbumVO(content);
		CompletableFuture<List<ArticleVO>> article = getArticleVO(content);
		CompletableFuture<List<Develop>> develop = getDevelopVO(content);
		//等待所有线程结束
		CompletableFuture<Void> result = CompletableFuture.allOf(article, album, develop);
		try {
			result.get(60, TimeUnit.SECONDS);
			searchVO.setArticle(article.get(60, TimeUnit.SECONDS));
			searchVO.setAlbum(album.get(60, TimeUnit.SECONDS));
			searchVO.setDevelop(develop.get(60, TimeUnit.SECONDS));
		} catch (InterruptedException | ExecutionException | TimeoutException e) {
			log.error("评论查询失败 {}", e.getMessage());
		}
		return searchVO;
	}
	
	private CompletableFuture<List<AlbumVO>> getAlbumVO(String content) {
		return CompletableFuture.supplyAsync(() -> {
			List<Album> list = albumMapper.selectList(new LambdaQueryWrapper<Album>()
					.like(Album::getTitle, content));
			return albumRepository.createVOList(list);
		}, executor);
	}
	
	private CompletableFuture<List<ArticleVO>> getArticleVO(String content) {
		return CompletableFuture.supplyAsync(() -> {
			List<Article> list = articleMapper.selectList(new LambdaQueryWrapper<Article>()
					.like(Article::getTitle, content));
			return articleRepository.createVOList(list);
		}, executor);
	}
	
	private CompletableFuture<List<Develop>> getDevelopVO(String content) {
		return CompletableFuture.supplyAsync(() -> developMapper.selectList(new LambdaQueryWrapper<Develop>()
				.like(Develop::getMessage, content)), executor);
	}
}
